import { Breadcrumb, Button, Card, Form, Radio, DatePicker, Table, Space, Tag, message } from 'antd'
import { EditOutlined, DeleteOutlined } from '@ant-design/icons'
import { deleteArticleByIdAPI, getArticlesAPI } from 'api/articles';
import { useState, useEffect, useRef } from 'react';
import { Link } from 'react-router-dom'
import Channel from 'components/Channel';
import history from 'utils/history';
import imagesError from 'assets/error.png'
const { RangePicker } = DatePicker;

export default function ArticleList() {
    const onChange = (date, dateString) => {
        console.log(date, dateString);
    }

    // 获取表单信息
    const onFinish = ({ status, channel_id, date }) => {
        const query = {}
        query.status = status !== -1 ? status : undefined
        query.channel_id = channel_id
        // 起始-截止时间
        if (date) {
            query.begin_pubdate = date[0].startOf('day').format('YYYY-MM-DD HH:mm:ss')
            query.end_pubdate = date[1].endOf('day').format('YYYY-MM-DD HH:mm:ss')
        }
        // 踢出undefined
        for (const key in query) {
            if (query[key] === undefined) {
                delete query[key]
            }
        }
        getArticlesList(query)
        queryRef.current = query
    }
    // 获取文章列表
    const [article, serArticle] = useState({})
    const getArticlesList = async (query) => {
        const res = await getArticlesAPI(query)
        serArticle(res.data)
    }

    const queryRef = useRef({})
    // 分页选中事件
    const pageChange = (page, per_page) => {
        queryRef.current = { ...queryRef.current, page, per_page }
        getArticlesList({ ...queryRef.current })
    }

    //删除文章
    const handleDelById = async (id) => {
        await deleteArticleByIdAPI(id)
        await getArticlesList({ ...queryRef.current })
        message.success('删除成功')
    }

    // 状态管理
    const articleStatus = [
        { id: -1, name: '全部', color: 'magenta' },
        { id: 0, name: '草稿', color: 'orange' },
        { id: 1, name: '待审核', color: 'red' },
        { id: 2, name: '审核通过', color: 'green' },
        { id: 3, name: '审核失败', color: 'cyan' },
    ]

    const columns = [
        {
            title: '封面',
            dataIndex: 'cover',
            render: (cover) => {
                return <img src={cover.images[0] || imagesError} alt='' style={{ width: 100, height: 60, objectFit: 'cover' }} />
            }
        },
        {
            title: '标题',
            dataIndex: 'title',
        },
        {
            title: '状态',
            dataIndex: 'status',
            render: (id) => {
                const obj = articleStatus.find(v => v.id === id)
                return <Tag color={obj.color} >{obj.name}</Tag>
            }
        },
        {
            title: '发布时间',
            dataIndex: 'pubdate',
        },
        {
            title: '阅读数',
            dataIndex: 'read_count',
        },
        {
            title: '评论数',
            dataIndex: 'comment_count',
        },
        {
            title: '点赞数',
            dataIndex: 'like_count',
        },
        {
            title: '操作',
            render: (item) => {
                return (
                    <Space>
                        <Button onClick={() => history.push(`/deit/${item.id}`)} type='primary' shape='circle' icon={<EditOutlined />} />
                        <Button onClick={() => handleDelById(item.id)} type='primary' danger shape='circle' icon={<DeleteOutlined />} />
                    </Space>
                )
            },
        },
    ]

    // 组件挂载时
    useEffect(() => {
        // 获取文章列表
        getArticlesList()
    }, [])



    return (
        <div>
            <div>
                <Card title={
                    <Breadcrumb>
                        <Breadcrumb.Item>
                            <Link to='/home'>首页</Link>
                        </Breadcrumb.Item>
                        <Breadcrumb.Item>文章列表</Breadcrumb.Item>
                    </Breadcrumb>}>
                    {/* 表单 */}
                    <Form onFinish={onFinish} initialValues={{ status: -1 }}>
                        <Form.Item label="状态" name="status" >
                            <Radio.Group >
                                <Radio value={-1}>全部</Radio>
                                <Radio value={0}>草稿</Radio>
                                <Radio value={1}>待审核</Radio>
                                <Radio value={2}>审核通过</Radio>
                                <Radio value={3}>审核失败</Radio>
                            </Radio.Group>
                        </Form.Item>
                        <Form.Item label="频道" name='channel_id'>
                            <Channel />
                        </Form.Item>
                        <Form.Item label="日期" name='date'>
                            <RangePicker onChange={onChange} />
                        </Form.Item>
                        <Form.Item>
                            <Button type='primary' htmlType='submit'>筛选</Button>
                        </Form.Item>
                    </Form>

                    {/* 筛选结果 */}
                    <h3>根据筛选条件共查询到{article.total_count}条结果:</h3>

                    {/* 表格 */}
                    <Table rowKey="id"
                        dataSource={article.results}
                        columns={columns}
                        pagination={{
                            position: ['bottomCenter'],
                            total: article.total_count,
                            onChange: pageChange,
                            current: article.page,
                            pageSize: article.per_page
                        }}
                    />
                </Card>
            </div>
        </div>
    )
}

